package com.zxw.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.zxw.common.web.annotation.InitSelectInfo;
import com.zxw.user.domain.dto.IdLabelDTO;
import com.zxw.user.domain.dto.MenuDTO;
import com.zxw.user.domain.entity.CompanyMenu;
import com.zxw.user.domain.entity.Menu;
import com.zxw.user.mapper.CompanyMenuMapper;
import com.zxw.user.service.CompanyMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Xuewei.Zhang
 * @since 2022-03-30
 */
@Service
@RequiredArgsConstructor
public class CompanyMenuServiceImpl extends ServiceImpl<CompanyMenuMapper, CompanyMenu> implements CompanyMenuService {

    private final CompanyMenuMapper companyMenuMapper;

    @Override
    @InitSelectInfo
    public List<MenuDTO> getMenuList(Menu menu) {
        List<MenuDTO> menuDTOList = companyMenuMapper.getAllByMenu(menu);
        List<MenuDTO> menuDTOS = recursiveGenreateMenuTableList(0l, menuDTOList);
        return menuDTOS;
    }


    @Override
    @InitSelectInfo
    public List<IdLabelDTO> getMenuSelectList(Menu menu) {
        List<MenuDTO> menuDTOList = companyMenuMapper.getAllByMenu(menu);
        return recursiveGenreateMenuSelectList(0l,menuDTOList);
    }


    private List<MenuDTO> recursiveGenreateMenuTableList(Long parenetId, List<MenuDTO> menuList) {
        List<MenuDTO> menuDTOS = new ArrayList<>();
        Optional.ofNullable(menuList).ifPresent(menus -> menus.stream().filter(menu -> menu.getParentId().equals(parenetId)).forEach(menu -> {
            MenuDTO menuDTO = new MenuDTO();
            BeanUtil.copyProperties(menu, menuDTO);
            List<MenuDTO> childrenList = recursiveGenreateMenuTableList(menuDTO.getId(), menuList);
            if (childrenList.size() > 0)
                menuDTO.setChildren(childrenList);
            menuDTOS.add(menuDTO);
        }));
        return menuDTOS;
    }


    private List<IdLabelDTO> recursiveGenreateMenuSelectList(Long parenetId, List<MenuDTO> menuList) {
        List<IdLabelDTO> menuDTOS = new ArrayList<>();
        Optional.ofNullable(menuList).ifPresent(menus -> menus.stream().filter(menu -> menu.getParentId().equals(parenetId)).forEach(menu -> {
            IdLabelDTO idLabelDTO = new IdLabelDTO();
            idLabelDTO.setId(menu.getId());
            idLabelDTO.setLabel(menu.getName());
            List<IdLabelDTO> childrenList = recursiveGenreateMenuSelectList(idLabelDTO.getId(), menuList);
            if (childrenList.size() > 0)
                idLabelDTO.setChildren(childrenList);
            menuDTOS.add(idLabelDTO);
        }));
        return menuDTOS;
    }
}
